"""
s=threading.Semaphore(1)#1代表计数器
s.acquire()#p操作，减一，如果小于0阻塞
s.release()#v操作，加一，如果大于等于0则说明有线程在等待

作者：xjcai
链接：https://leetcode-cn.com/problems/print-foobar-alternately/solution/python3-xin-hao-liang-pvcao-zuo-by-xjcai/
来源：力扣（LeetCode）
著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
"""
import threading
class FooBar:
    def __init__(self, n):
        self.n = n
        self.first_lock = threading.Lock()
        self.second_lock = threading.Lock()
        self.s1=threading.Semaphore(1)
        self.s2=threading.Semaphore(0)

    def foo(self, printFoo: 'Callable[[], None]') -> None:
        
        for i in range(self.n):
            self.s1.acquire()
            printFoo()
            self.s2.release()


    def bar(self, printBar: 'Callable[[], None]') -> None:
        
        for i in range(self.n):
            self.s2.acquire()
            printBar()
            self.s1.release()

if __name__ == "__main__":
    def printBar():
        print("Bar")
    def printFoo():
        print("Foo")
    foo_bar = FooBar(5)
    t1 = threading.Thread(target=foo_bar.bar, args=(printBar,))
    t2 = threading.Thread(target=foo_bar.foo, args=(printFoo,))

    t1.start()
    t2.start()
